package com.bs.visitservice.controller.seller;

import com.auth0.jwt.interfaces.Claim;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bs.visitservice.cache.impl.JedisLoginCache;
import com.bs.visitservice.constant.CacheContant;
import com.bs.visitservice.entity.SellerLoginInfo;
import com.bs.visitservice.service.SellerLoginInfoService;
import com.bs.visitservice.utils.ImageCodeUtil;
import com.bs.visitservice.utils.JwtUtil;
import com.bs.visitservice.utils.Result;
import com.bs.visitservice.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;

/**
 * 商家端注册登陆
 */
@RestController
public class SellerLoginController {

    @Autowired
    private SellerLoginInfoService sellerLoginInfoService;

    @Autowired
    private JedisLoginCache jedisLoginCache;
    /**
     * 商家登陆，返回tokenId
     * @param request
     * @param cond
     * @return
     */
    @RequestMapping(value = "/sellerpublic/login",method = RequestMethod.POST)
    public Result login(HttpServletRequest request,@RequestBody Map cond){
        String verifyCode = (String)request.getSession().getAttribute("verifyCode");
        String pageVerifyCode = (String)cond.get("verifyCode");
        if(!verifyCode.equalsIgnoreCase(pageVerifyCode)){
            return Result.error("验证码不正确，请重新输入！");
        }
        SellerLoginInfo sli =  (SellerLoginInfo)ResultUtil.transObject(cond,SellerLoginInfo.class);
        LambdaQueryWrapper<SellerLoginInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SellerLoginInfo::getLoginNo,sli.getLoginNo()).eq(SellerLoginInfo::getPassword,sli.getPassword());
        List<SellerLoginInfo> sellerLoginInfoList = sellerLoginInfoService.list(wrapper);
        if(sellerLoginInfoList.size() > 0){
            sli = sellerLoginInfoList.get(0);
            Map<String,Object> claims = new HashMap<>();
            claims.put("loginNo",sli.getNo());
            claims.put("role","seller");
            Calendar c = Calendar.getInstance();
            c.add(Calendar.YEAR,1);
            //生成token
            String tokenId = JwtUtil.genToken(claims,c.getTime());
            //设置商家端tokenId失效时间30分钟
            jedisLoginCache.putCache(tokenId,sli.getNo(),30*60);
            jedisLoginCache.putMapCacheOne(CacheContant.SELLER_LOGIN_STATE,String.valueOf(sli.getNo()),true);
            List<Map<String,Object>> data = new ArrayList<>();
            Map<String,Object> dataMap = new HashMap<>();
            dataMap.put("tokenId", tokenId);
            dataMap.put("no", sli.getNo());
            data.add(dataMap);
            return Result.success(data);
        }
        return Result.error(null);

    }

    /**
     * 商家创建登陆账号密码
     * @param
     * @return
     */
    @RequestMapping(value = "/sellerpublic/regist",method = RequestMethod.POST)
    public Result regist(HttpServletRequest request,@RequestBody  Map cond){
        String verifyCode = (String)request.getSession().getAttribute("verifyCode");
        String pageVerifyCode = (String)cond.get("verifyCode");
        if(!verifyCode.equalsIgnoreCase(pageVerifyCode)){
            return Result.error("验证码不正确，请重新输入！");
        }
        SellerLoginInfo sli =  (SellerLoginInfo)ResultUtil.transObject(cond,SellerLoginInfo.class);
        LambdaQueryWrapper<SellerLoginInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SellerLoginInfo::getLoginNo,sli.getLoginNo());
        SellerLoginInfo one = sellerLoginInfoService.getOne(wrapper);
        if(one != null){
            return Result.error("用户名已存在！");
        }
        boolean isSuc = sellerLoginInfoService.save(sli);
        if(isSuc){
            return Result.success(null);
        }
        return Result.error(null);

    }

    /**
     * 获取验证码图片
     * @param response
     * @param request
     */
    @RequestMapping(value = "/sellerpublic/getVerifyCode",method = RequestMethod.GET)
    public void getVerificationCode(HttpServletResponse response, HttpServletRequest request) {
        try {
            int width = 200;
            int height = 69;
            BufferedImage verifyImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            String randomText = ImageCodeUtil.drawRandomText(width, height, verifyImg);
            request.getSession().setAttribute("verifyCode", randomText);
            response.setContentType("image/png");//必须设置响应内容类型为图片，否则前台不识别
            OutputStream os = response.getOutputStream(); //获取文件输出流
            ImageIO.write(verifyImg, "png", os);//输出图片流
            os.flush();
            os.close();//关闭流
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
